﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Apollo.Web;
using Apollo.Core;
using Apollo;

namespace Apollo.Website
{
    public partial class Controls_Edit_FormItemTextArea : System.Web.UI.UserControl, IFormItem
    {
        public FormItem Item { get; set; }

        public object TargetObject { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.LabelPropertyName.CssClass = "property_name";

            if (!this.IsPostBack)
            {
                this.LabelPropertyName.Text = this.Item.Projection.DisplayName;

                if (this.TargetObject != null)
                {
                    object obj = this.Item.Projection.Apply(this.TargetObject);

                    if (obj != null)
                        this.TextBoxPropertyValue.Text = obj.ToString();
                } else {
                    this.TextBoxPropertyValue.Text = this.Item.Projection.EntityProperty.DefaultValue;
                }

                this.TextBoxPropertyValue.Enabled = (this.Item.Type != FormItemType.ReadOnly);

                if (!this.TextBoxPropertyValue.Enabled)
                    this.TextBoxPropertyValue.CssClass = "property_value_disabled";
            }
        }

        public ActionMessage Save(object obj)
        {
            if (this.Item.Type == FormItemType.ReadOnly)
                return null;
            else if (this.Item.Type == FormItemType.Required && this.TextBoxPropertyValue.Text == "")
            {
                LabelPropertyName.CssClass = "property_name_error";
                return new ActionMessage(this.Item.Projection.DisplayName + " can not be null", ActionMessageType.Error);
            }

            this.Item.Projection.SetValue(obj, this.TextBoxPropertyValue.Text);

            return null;
        }
    }
}